import React, { Component } from 'react';
import { Input, Transfer, Button, Table, Checkbox, Card } from 'antd';
// import difference from 'lodash/difference';
import { similarlibQuestionList } from '@/services/similarExt';
import styles from './QuestionLib.less';
const { Search } = Input;

const TableTransfer = ({ leftColumns, rightColumns, ...restProps }) => (
    <Transfer {...restProps} showSelectAll={false} rowKey={record => record.id}>
        {/* {({
            direction,
            filteredItems,
            onItemSelectAll,
            onItemSelect,
            selectedKeys: listSelectedKeys,
            disabled: listDisabled,
        }) => {
            const columns = direction === 'left' ? leftColumns : rightColumns;
            const onCheckAllChange = () => {
                console.log(filteredItems, restProps.rightData);
                let data = direction === 'left' ? filteredItems : restProps.rightData;
                let dataId = listSelectedKeys.length < data.length ? data.map(item => item.id) : null;
                let datafKeys = dataId ? difference(dataId, listSelectedKeys) : difference(listSelectedKeys, dataId);
                onItemSelectAll(datafKeys, dataId);
            };
            const disabled = direction === 'left'
                ? restProps.total === 0 ? true : false
                : filteredItems.length === 0 ? true : false;
            const checked = direction === 'left'
                ? restProps.total > 0 ? filteredItems.length === listSelectedKeys.length ? true : false : false
                : filteredItems.length > 0 ? restProps.rightData.length === listSelectedKeys.length ? true : false : false;
            const indeterminate = direction === 'left'
                ? restProps.total > 0 ? filteredItems.length !== listSelectedKeys.length && listSelectedKeys.length !== 0 ? true : false : false
                : filteredItems.length > 0 ? restProps.rightData.length !== listSelectedKeys.length && listSelectedKeys.length !== 0 ? true : false : false;
            const rowSelection = {
                columnTitle: () => {
                    return <Checkbox indeterminate={indeterminate} onChange={onCheckAllChange} disabled={disabled} checked={checked}>全选</Checkbox>
                },
                columnWidth: 80,
                onSelectAll(selected, selectedRows) {
                    const treeSelectedKeys = selectedRows.filter(item => !item.disabled).map(({ id }) => id);
                    const diffKeys = selected
                        ? difference(treeSelectedKeys, listSelectedKeys)
                        : difference(listSelectedKeys, treeSelectedKeys);
                    onItemSelectAll(diffKeys, selected);
                },
                onSelect({ id }, selected) {
                    onItemSelect(id, selected);
                },
                selectedRowKeys: listSelectedKeys,
            };

            return (
                <Table
                    rowSelection={rowSelection}
                    columns={columns}
                    dataSource={direction === 'left' ? filteredItems : restProps.rightData}
                    size="small"
                    style={{ pointerEvents: listDisabled ? 'none' : null }}
                    rowKey="id"
                    pagination={{
                        total: direction === 'left' ? restProps.total : filteredItems.length,
                        onChange: direction === 'left' ? restProps.onPageChange : null,
                        pageSize: 100,
                    }}
                    scroll={{ y: '60vh' }}
                    loading={direction === 'left' ? restProps.loading : false}
                />
            );
        }} */}
    </Transfer>
);

class QuestionLib extends Component {
    state = {
        questions: null,
        loading: false,
        query: {
            size: 100,
            current: 1,
            question: '',
        },
        targetKeys: [],
        rightData: [],
        sourceSelectedKeys: [],
        sourceSelectedRows: [],
        targetSelectedKeys: [],
    };

    componentDidMount() {
        this.fetchData();
        if (this.props.onRef) {
            this.props.onRef(this);
        };
        setTimeout(() => {
            document.querySelectorAll("#tableBody .ant-table-column-sorter")[0].innerText = '全部';
            document.querySelectorAll("#tableBody .ant-table-column-sorter")[0].style.margin = '0 0 0 5px';
            document.querySelectorAll("#tableBody .ant-table-header-column>div")[0].style.display = 'flex';
            document.querySelectorAll("#tableBody .ant-table-header-column>div")[0].style.width = '49px';

            document.querySelectorAll("#tableBody .ant-table-column-sorter")[2].innerText = '全部';
            document.querySelectorAll("#tableBody .ant-table-column-sorter")[2].style.margin = '0 0 0 5px';
            document.querySelectorAll("#tableBody .ant-table-header-column>div")[2].style.display = 'flex';
            document.querySelectorAll("#tableBody .ant-table-header-column>div")[2].style.width = '49px';
        }, 500)
    }

    onclose = () => {
        this.setState({
            questions: null,
            loading: false,
            query: {
                size: 100,
                current: 1,
                question: '',
            },
            targetKeys: [],
            rightData: [],
            sourceSelectedKeys: [],
            targetSelectedKeys: [],
        })
    }

    fetchData = async () => {
        const { query, loading } = this.state;
        let { questions } = this.state;
        this.setState({ loading: true });
        questions = await similarlibQuestionList(query);
        this.setState({ questions, loading: false });
    };

    handleSearch = value => {
        this.setState(
            {
                query: {
                    ...this.state.query,
                    current: 1,
                    size: 100,
                    question: value,
                },
            },
            this.fetchData
        );
    };

    onChange = (targetKeys) => {
        let { rightData } = this.state;
        // const { questions } = this.state;
        const { onChange } = this.props;
        // if (direction === 'right') {
        //     rightData = questions.records.filter(item => targetKeys.indexOf(item.id) > -1);
        // } else {
        //     rightData = rightData.filter(item => moveKeys.indexOf(item.id) == -1);
        // }
        this.setState({ targetKeys, rightData }, () => {
            onChange(rightData);
        });
    };

    clearTargetKeys = () => {
        const { targetSelectedKeys } = this.state;
        let { targetKeys, rightData } = this.state;
        rightData = rightData.filter(item => targetSelectedKeys.indexOf(item.id) == -1);
        targetKeys = targetKeys.filter(item => targetSelectedKeys.indexOf(item) == -1);
        this.setState({ targetKeys, rightData, targetSelectedKeys: [] }, () => {
            this.onChange(targetKeys)
        });
    };

    selectAll = () => {
        const { questions, sourceSelectedKeys, sourceSelectedRows } = this.state;
        let { targetKeys, rightData } = this.state;
        // const newTargetKeys = questions.records.filter(item => ((sourceSelectedKeys.indexOf(item.id) > -1) && !(targetKeys.indexOf(item.id) > -1)));
        // targetKeys = [...targetKeys, ...sourceSelectedKeys.filter(item => !(targetKeys.indexOf(item) > -1))];
        // rightData = [ ...rightData, ...newTargetKeys];
        targetKeys = sourceSelectedRows.map(item => item.id);
        rightData = sourceSelectedRows;
        this.setState({ targetKeys, rightData }, () => {
            this.onChange(targetKeys)
        });
    };

    onPageChange = (current, size) => {
        this.setState({ query: { ...this.state.query, current, size } }, () => {
            this.fetchData();
        });
    };

    triggerOnItemSelect = (sourceSelectedKeys, targetSelectedKeys) => {
        let {
            sourceSelectedKeys: newSourceSelectedKeys,
            targetSelectedKeys: newTargetSelectedKeys,
        } = this.state;
        newSourceSelectedKeys = sourceSelectedKeys;
        newTargetSelectedKeys = targetSelectedKeys;

        this.setState({
            sourceSelectedKeys,
            targetSelectedKeys,
        });
    };

    render() {
        const { questions, targetKeys, rightData, sourceSelectedKeys, targetSelectedKeys, loading, sourceSelectedRows, query } = this.state;
        const leftTableColumns = [
            { dataIndex: 'question', title: '问题库' },
        ];
        const rightTableColumns = [
            { dataIndex: 'question', title: '待添加' },
        ];
        const rowLeftSelection = {
            type: 'checkbox',
            selectedRowKeys: sourceSelectedKeys, //告诉插件我们点击的哪一行
            onChange: (selectedRowKeys, selectedRows) => {
                // console.log(selectedRowKeys, selectedRows);
                let rows = [
                    ...sourceSelectedRows.filter(
                        (item,index) => (
                            (selectedRowKeys.indexOf(item.id) > -1) && (sourceSelectedRows.indexOf(item) === index) && (selectedRows.map(row => row.id).indexOf(item.id) === -1)
                        )
                    ),
                    ...selectedRows
                ];
                // console.log(selectedRowKeys, rows);
                this.setState({ sourceSelectedKeys: selectedRowKeys, sourceSelectedRows: rows, });
            },
            getCheckboxProps: record => ({
                disabled: targetKeys.indexOf(record.id) > -1, // Column configuration not to be checked
                name: record.question,
            }),
        };
        const rowRightSelection = {
            type: 'checkbox',
            selectedRowKeys: targetSelectedKeys, //告诉插件我们点击的哪一行
            onChange: (selectedRowKeys, selectedRows) => {
                this.setState({ targetSelectedKeys: selectedRowKeys, });
            },
        };

        return (
            <div>
                <Search placeholder="输入问题关键词" onSearch={this.handleSearch} style={{ width: 350 }} />
                <div className={styles.tableBody} id="tableBody">
                    <Card
                        style={{ height: '100%' }}
                        title={
                            <>
                                {sourceSelectedKeys.length > 0 ? (
                                    <span>已选中 {sourceSelectedKeys.length} 项</span>
                                ) : null}
                            </>
                        }
                        extra={
                            <Button size="small" onClick={this.selectAll} disabled={sourceSelectedKeys.length === 0 || sourceSelectedKeys.length === rightData.length}>批量添加</Button>
                        }
                    >
                        <Table
                            dataSource={questions?.records}
                            rowKey="id"
                            loading={loading}
                            columns={leftTableColumns}
                            rowSelection={rowLeftSelection}
                            size="small"
                            scroll={{ y: 'calc(60vh - 60px)' }}
                            pagination={{
                                total: questions?.total,
                                pageSize: 100,
                                current: query.current,
                                onChange: this.onPageChange,
                            }}
                        />
                    </Card>
                    <div style={{ margin: '0 10px', lineHeight: '32px' }}>
                        <Button type="primary" icon="right" size="small" onClick={this.selectAll} disabled={sourceSelectedKeys.length === 0 || sourceSelectedKeys.length === rightData.length} />
                        <Button type="primary" icon="left" size="small" onClick={this.clearTargetKeys} disabled={targetSelectedKeys.length === 0} />
                    </div>
                    <Card
                        style={{ height: '100%' }}
                        title={
                            <>
                                {targetSelectedKeys.length > 0 ? (
                                    <span>{targetSelectedKeys.length} / {rightData.length} 项</span>
                                ) : (
                                    <span>{rightData.length} 项</span>
                                )}
                            </>
                        }
                        extra={
                            <Button size="small" onClick={this.clearTargetKeys} disabled={targetSelectedKeys.length === 0}>批量移除</Button>
                        }
                    >
                        <Table
                            dataSource={rightData}
                            rowKey="id"
                            columns={rightTableColumns}
                            rowSelection={rowRightSelection}
                            size="small"
                            scroll={{ y: 'calc(60vh - 60px)' }}
                            pagination={{
                                total: rightData.length,
                                pageSize: 100,
                            }}
                        />
                    </Card>
                </div>
                {/* <TableTransfer
                    dataSource={questions?.records}
                    targetKeys={targetKeys}
                    disabled={false}
                    showSearch={false}
                    onChange={this.onChange}
                    leftColumns={leftTableColumns}
                    rightColumns={rightTableColumns}
                    style={{ marginTop: 20 }}
                    listStyle={{
                        width: 350,
                    }}
                    titles={[
                        <Button size="small" onClick={this.selectAll} disabled={sourceSelectedKeys.length === 0}>批量添加</Button>,
                        <Button size="small" onClick={this.clearTargetKeys} disabled={targetSelectedKeys.length === 0}>批量移除</Button>,
                    ]}
                    total={questions?.total}
                    onPageChange={this.onPageChange}
                    rightData={rightData}
                    onSelectChange={this.triggerOnItemSelect}
                    loading={loading}
                /> */}
            </div>
        );
    }
}

export default QuestionLib;
